import markerJson from "../../../utils/video.json";
import { getVideoUrlByCameraId } from "@/api/charge/gate";
import "video.js/dist/video-js.css";
import videojs from "video.js";

var scatterYellow = null;
var triangleZMarker = null;
var zMarker = null;
// 摄像头
export default class Marker {
  constructor(map, Loca, loca, AMap, router, dataNew, isFlag) {
    this.layerIcon = null;
    this.infoWindow = null;
    this.router = router;
    this.dataNew = dataNew;
    if (isFlag) {
      this.hideIcon();
    } else if (this.layerIcon) {
      this.layerIcon.show();
    } else {
      this.init(map, Loca, loca, AMap);
    }
  }

  init(map, Loca, loca, AMap) {
    let tollgatePoint = [];
    markerJson.forEach((item) => {
      if (item.latitude && item.longitude) {
        tollgatePoint.push({
          type: "Feature",
          geometry: {
            type: "Point",
            coordinates: [item.latitude, item.longitude],
          },
          properties: { ...item },
        });
      }
    });
    // this.dataNew.forEach((item) => {
    //   if (item.Latitude && item.Longitude) {
    //     tollgatePoint.push({
    //       type: "Feature",
    //       geometry: {
    //         type: "Point",
    //         coordinates: [item.Latitude, item.Longitude],
    //       },
    //       properties: { ...item, name: 13 },
    //     });
    //     // this.addMarker(item,AMap,map);
    //   }
    //   //
    // });

    // console.log(tollgatePoint, "tollgatePoint");

    // let json = {
    //   type: "FeatureCollection",
    //   features: [
    //     {
    //       type: "Feature",
    //       geometry: {
    //         type: "Point",
    //         coordinates: [item.Latitude, item.Longitude],
    //       },
    //       properties:{
    //         name:"摄像头名称",
    //         location:"位置"
    //       }
    //     },
    //     {
    //       type: "Feature",
    //       geometry: {
    //         type: "Point",
    //         coordinates: [item.Latitude, item.Longitude],
    //       },
    //       properties:{
    //         name:"摄像头名称",
    //         location:"位置"
    //       }
    //     },
    //   ],
    // };
    var geoPoint = new Loca.GeoJSONSource({
      data: {
        type: "FeatureCollection",
        features: tollgatePoint,
      },
      // data:testJson
    });

    this.getIconLocation(map, Loca, loca, geoPoint);
  }

  getPointName(map, Loca, loca, geoPoint, layerIcon) {
    // 文字主体图层
    var zMarker = new Loca.ZMarkerLayer({
      loca: loca,
      zIndex: 120,
      depth: false,
      visible: false,
    });
    zMarker.setSource(geoPoint);
    zMarker.setStyle({
      content: (i, feat) => {
        var props = feat.properties;
        var leftColor =
          props.price < 60000 ? "rgba(0, 28, 52, 0.6)" : "rgba(33,33,33,0.6)";
        var rightColor =
          props.price < 60000 ? "#038684" : "rgba(172, 137, 51, 0.3)";
        var borderColor =
          props.price < 60000 ? "#038684" : "rgba(172, 137, 51, 1)";
        return (
          '<div style="width: 620px; height: 228px; padding: 0 0;">' +
          '<p style="display: block; height:80px; line-height:80px;font-size:40px;background-image: linear-gradient(to right, ' +
          leftColor +
          "," +
          leftColor +
          "," +
          rightColor +
          ",rgba(0,0,0,0.4)); border:4px solid " +
          borderColor +
          '; color:#fff; border-radius: 15px; text-align:center; margin:0; padding:5px;">' +
          props["name"] +
          '</p><span style="width: 130px; height: 130px; margin: 0 auto; display: block; background: url(https://a.amap.com/Loca/static/loca-v2/demos/images/prism_' +
          (props["price"] < 60000 ? "blue" : "yellow") +
          '.png);"></span></div>'
        );
      },
      unit: "meter",
      rotation: 0,
      alwaysFront: true,
      size: [620 / 2, 222 / 2],
      altitude: 0,
    });

    var triangleZMarker = new Loca.ZMarkerLayer({
      loca: loca,
      zIndex: 119,
      depth: false,
      visible: false,
    });

    triangleZMarker.setSource(geoPoint);
    triangleZMarker.setStyle({
      content: (i, feat) => {
        return (
          '<div style="width: 120px; height: 120px; background: url(https://a.amap.com/Loca/static/loca-v2/demos/images/triangle_' +
          (feat.properties.price < 60000 ? "blue" : "yellow") +
          '.png);"></div>'
        );
      },
      unit: "meter",
      rotation: 0,
      alwaysFront: true,
      size: [60, 60],
      altitude: 15,
    });
    triangleZMarker.addAnimate({
      key: "altitude",
      value: [0, 1],
      random: true,
      transform: 1000,
      delay: 2000,
      yoyo: true,
      repeat: 999999,
    });

    // 呼吸点 金色
    var scatterYellow = new Loca.ScatterLayer({
      loca,
      zIndex: 110,
      opacity: 1,
      visible: true,
      zooms: [2, 26],
      depth: false,
      visible: false,
    });

    scatterYellow.setSource(geoPoint);
    scatterYellow.setStyle({
      unit: "meter",
      size: function (i, feat) {
        return feat.properties.price > 60000 ? [90, 90] : [0, 0];
      },
      texture:
        "https://a.amap.com/Loca/static/loca-v2/demos/images/scan_yellow.png",
      altitude: 20,
      duration: 2000,
      animate: true,
    });

    // 启动帧
    loca.animate.start();

    // 监听zoomend事件
    // map.on("zoomend", () => {
    //   // 获取当前缩放级别

    //   const currentZoom = map.getZoom();
    //   console.log("缩放",currentZoom)
    //   if (currentZoom > 16) {
    //     layerIcon ? layerIcon.hide() : "";
    //     this.infoWindow?this.infoWindow.close() :''
    //     scatterYellow.show();
    //     triangleZMarker.show();
    //     zMarker.show();
    //   } else {
    //     layerIcon ? layerIcon.show() : "";

    //     scatterYellow.hide();
    //     triangleZMarker.hide();
    //     zMarker.hide();
    //   }
    // });
    // map.on('dragend', () => {
    //   const center = map.getCenter(); // 获取新的中心点
    //   console.log('地图拖拽后的中心点：', center);
    //   // 你可以在这里根据新的中心点进行其他操作
    // });

    // map.on('mouseover', (e) => {
    //   console.log("点击跳转大屏",e)
    //     const feat = layerIcon.queryFeature(e.pixel.toArray());
    //     if (feat) {
    //       const content = `<div class="textcus">${feat.properties.name}</div>`;
    //        this.infoWindow = new AMap.InfoWindow({
    //         isCustom: true,
    //         content: content,  //传入 dom 对象，或者 html 字符串
    //         offset: new AMap.Pixel(10, -10)
    //       });
    //       this.infoWindow.open(map, e.lnglat);
    //     }
    // });

    map.on("click", (e) => {
      const feat = layerIcon.queryFeature(e.pixel.toArray());
      if (feat) {
      }
    });

    layerIcon.on("complete", () => {
      var normalMarker = new AMap.Marker({
        offset: [8, 12],
      });
      var labelMarkers = layerIcon.getLabelsLayer().getAllOverlays();
      for (let marker of labelMarkers) {
        marker.on("mouseover", (e) => {
          var position = e.data.data && e.data.data.position;
          if (position) {
            normalMarker.setContent(
              '<div class="amap-info-window">地址：' +
                marker.getExtData().address +
                "</div>"
            );
            normalMarker.setPosition(position);
            map.add(normalMarker);
          }
        });
        marker.on("mouseout", () => {
          map.remove(normalMarker);
        });
      }
    });
  }

  options() {
    return {
      html5: {
        hls: {
          overrideNative: false,
        },
        nativeVideoTracks: true,
        nativeAudioTracks: true,
        nativeTextTracks: true,
      },
      autoplay: true, // true,浏览器准备好时开始播放。
      muted: false, // 默认情况下将会消除音频。
      loop: false, // 导致视频一结束就重新开始。
      controls: true,
      preload: "auto", // auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
      fluid: true, // 当true时，将按比例缩放以适应其容器。
      type: "application/x-mpegURl",
      notSupportedMessage: "此视频暂无法播放，请稍后再试", // 无法播放媒体源时显示的默认信息。
      textTrackDisplay: false,
    };
  }

  getIconLocation(map, Loca, loca, geoPoint) {
    map.on("dragend", () => {
      const center = map.getCenter(); // 获取新的中心点
      console.log("地图拖拽后的中心点：", center);
      // 你可以在这里根据新的中心点进行其他操作
    });

    this.layerIcon = new Loca.LabelsLayer({
      zIndex: 10,
      opacity: 1,
      visible: true,
      zooms: [8, 15],
    });
    this.layerIcon.setSource(geoPoint);
    let url = new URL(`../../../assets/images/icon54.png`, import.meta.url)
      .href;
    this.layerIcon.setStyle({
      icon: {
        type: "image",
        image: url,
        size: [21, 26],
        anchor: "center",
      },
      extData: (index, feat) => {
        return feat.properties;
      },
    });
    loca.add(this.layerIcon);

    this.layerIcon.on("complete", () => {
      var normalMarker = new AMap.Marker({
        offset: [10, -10],
      });
      var labelMarkers = this.layerIcon.getLabelsLayer().getAllOverlays();
      for (let marker of labelMarkers) {
        marker.on("mouseover", (e) => {
          map.remove(normalMarker);
          var position = e.data.data && e.data.data.position;
          if (position) {
            normalMarker.setContent(
              '<div class="textcusNew">监控位置：' +
                marker.getExtData().name +
                "</div>"
            );
            normalMarker.setPosition(position);
            map.add(normalMarker);
          }
        });
        marker.on("click", (e) => {
          // 点击弹出视频
          map.remove(normalMarker);
          var position2 = e.data.data && e.data.data.position;
          // '<div class="narrow-videonew" onclick="bindShowVideo()" id="id_video1" ref="myElement1" style="width:180px,height:120px"><div class="play-icon"></div><div class="full-icon"></div> </div>'
          if (position2) {
            //  let VideoUrl= window.getList(marker.getExtData().code)
            getVideoUrlByCameraId({ code: marker.getExtData().code }).then(
              (res) => {
                if (res.code == 200 && res.data && res.data.VideoUrl) {
                  // VideoUrl.value = res.data.VideoUrl; `<${VideoPlayer} src="${res.data.VideoUrl}" id="videoPlayer" class="narrow-videonew" ref="RefChild" style="width:180px,height:120px" muted />`
                  normalMarker.setContent(
                    '<div style="width:180px;height:120px"> <video id="videoPlayerNew'+marker.getExtData().code+'"  class="video-js" style="width:100%;height:100%"><source  src="' +
                      res.data.VideoUrl +
                      '"/></video></div>'
                  );
                  normalMarker.setPosition(position2);
                  map.add(normalMarker);

                  let player = videojs("videoPlayerNew"+marker.getExtData().code, this.options(), () => {
                    player.play();
                    player.on("canplaythrough", function (event) {});
                    player.on("play", function () {
                      console.log("视频准备播放");
                    });
                    player.on("pause", function (event) {
                      player.dispose();
                    });
                  });
                }
              }
            );
          }
        });
      }
    });

    // this.getPointName(map, Loca, loca, geoPoint, layerIcon);
  }

  hideIcon() {
    this.layerIcon.hide();
    // if (player) {
    //   player.dispose();
    // }
    // this.infoWindow.hide()
    // scatterYellow.hide();
    // triangleZMarker.hide();
    // zMarker.hide();
  }

  showIcon() {
    this.layerIcon.show();
  }
}
